# -*- coding: utf-8 -*-
from db.mysql import MysqlClient
import json, requests, execjs
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode
from itertools import product


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "个人交通意外保险"
        self.table = "accident"

    # 生成数据
    def genProductInfo(self):
        plan = {

            "plan": [

                {

                    "airplane_death": "800000",
                    "train_death": "300000",
                    "ship_disability": "300000",
                    "passenger_death": "100000"
                },
                {

                    "airplane_death": "1000000",
                    "train_death": "300000",
                    "ship_disability": "300000",
                    "passenger_death": "100000"
                },
                {

                    "airplane_death": "1000000",
                    "train_death": "1000000",
                    "ship_disability": "1000000",
                    "passenger_death": "500000"
                }

            ],
            "expire": ["7天", "一个月", "三个月", "一年"],

        }
        for v in product(plan["plan"], plan["expire"]):
            index = plan["plan"].index(v[0])

            data = {
                "days": v[1],
                "index": index,
                "plan": v[0]
            }
            yield data

    # 获取数据
    def requestJson(self):

        # 初始化
        init = {'name': '个人交通意外保险', 'company': '燕赵财险', 'days': '7d', 'people_count': '1', 'price': "3.8",
                'airplane_death': '550000', 'train_death': '200000', 'ship_disability': '200000',
                'passenger_death': '50000'}

        self.mergeTable(init)

        for v in self.genProductInfo():

            data = {

                "comboCodeList[0]": "20160624001000004",
                "comboCodeList[1]": "20160624001000001",
                "comboCodeList[2]": "20160624001000002",
                "comboCodeList[3]": "20160624001000003",
                "duringInsurance": v["days"],

            }
            payload = urlencode(data).replace("+", "")
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
            if r.status_code == 200:

                price = self.calcPremium(r.json(), v["index"] + 1)

                price = Helper.decimalParse(price)

                if v["days"] == "7天":

                    days = "7d"
                elif v["days"] == "一个月":

                    days = "1m"

                elif v["days"] == "三个月":

                    days = "3m"

                else:

                    days = "1y"

                data = {
                    "name": self.name,
                    "company": "燕赵财险",
                    "days": days,
                    "people_count": "1",
                    "price": price

                }

                data.update(v["plan"])
                self.mergeTable(data)

    # 计算保费
    def calcPremium(self, msg, num):

        js = '''
        var  productData = {
          "productName": "个人交通意外保险",
          "productCode": "20160624001",
          "riskCode": "1953000027",
          "isLongItem": true,
          "comboShowType": "1",
          "insureDateType": "0",
          "insureDate": "7天,一个月,三个月,一年",
          "insureDateMin": 0,
          "insureDateMax": 0,
          "ageCheckType": "0",
          "ageMin": 18,
          "ageMax": 65,
          "calType": "3",
          "isCheckInsured": false,
          "checkInsuredType": "1",
          "combo": [
            {
              "comboType": "20160624001000004",
              "comboName": "女神款",
              "unit": "",
              "amount": 0,
              "adultAmount": 0,
              "minorAmount": 0,
              "comboDetails": [
                {
                  "price": "55万元",
                  "other": "飞机意外伤害身故和残疾",
                  "value": "5500000"
                },
                {
                  "price": "20万元",
                  "other": "火车意外伤害身故和残疾",
                  "value": "2000000"
                },
                {
                  "price": "20万元",
                  "other": "轮船意外伤害身故和残疾",
                  "value": "2000000"
                },
                {
                  "price": "5万元",
                  "other": "汽车意外伤害身故和残疾",
                  "value": "50000"
                }
              ]
            },
            {
              "comboType": "20160624001000001",
              "comboName": "基础款",
              "unit": "",
              "amount": 17,
              "adultAmount": 0,
              "minorAmount": 0,
              "comboDetails": [
                {
                  "price": "80万元",
                  "other": "飞机意外伤害身故和残疾",
                  "value": "8000000"
                },
                {
                  "price": "30万元",
                  "other": "火车意外伤害身故和残疾",
                  "value": "3000000"
                },
                {
                  "price": "30万元",
                  "other": "轮船意外伤害身故和残疾",
                  "value": "3000000"
                },
                {
                  "price": "10万元",
                  "other": "汽车意外伤害身故和残疾",
                  "value": "100000"
                }
              ]
            },
            {
              "comboType": "20160624001000002",
              "comboName": "经典款",
              "unit": "",
              "amount": 24.75,
              "adultAmount": 0,
              "minorAmount": 0,
              "comboDetails": [
                {
                  "price": "100万元",
                  "other": "飞机意外伤害身故和残疾",
                  "value": "10000000"
                },
                {
                  "price": "50万元",
                  "other": "火车意外伤害身故和残疾",
                  "value": "5000000"
                },
                {
                  "price": "50万元",
                  "other": "轮船意外伤害身故和残疾",
                  "value": "5000000"
                },
                {
                  "price": "15万元",
                  "other": "汽车意外伤害身故和残疾",
                  "value": "150000"
                }
              ]
            },
            {
              "comboType": "20160624001000003",
              "comboName": "尊贵款",
              "unit": "",
              "amount": 72,
              "adultAmount": 0,
              "minorAmount": 0,
              "comboDetails": [
                {
                  "price": "100万元",
                  "other": "飞机意外伤害身故和残疾",
                  "value": "10000000"
                },
                {
                  "price": "100万元",
                  "other": "火车意外伤害身故和残疾",
                  "value": "10000000"
                },
                {
                  "price": "100万元",
                  "other": "轮船意外伤害身故和残疾",
                  "value": "10000000"
                },
                {
                  "price": "50万元",
                  "other": "汽车意外伤害身故和残疾",
                  "value": "500000"
                }
              ]
            }
          ]
        }
        function calcPremium( msg ,num ){
        
            for(var i = 0; i < productData.combo.length;i ++){
                productData.combo[i].amount = msg.premiums[i];
                var premium = productData.combo[i].amount * 1;
                
                if ( i == num ){
                
                return premium
                
                }
                
                }
        }
        
        '''
        cxt = execjs.compile(js)

        price = cxt.call("calcPremium", msg, num)
        return price

    # 合并表格
    def mergeTable(self, data):

        SQL = 'INSERT INTO `' + TABLE_ACCIDENT + '`(`name`,`company`,`days`,`people_count`,`price`,`airplane_death`,`train_death`,`ship_disability`,`passenger_death`)VALUES("{name}","{company}","{days}","{people_count}","{price}","{airplane_death}","{train_death}","{ship_disability}","{passenger_death}")'

        print(SQL.format(**data))

        self.mysql.cursor.execute(SQL.format(**data))
        self.mysql._conn.commit()
